package com.tee.live.im.core.server.common;

import com.tee.im.constants.ImConstants;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

public class ImMsgDecode extends ByteToMessageDecoder {

    private final int BASE_LEN = 2 + 4 + 4; // magic(2) + code(4) + len(4)

    @Override
    protected void decode(final ChannelHandlerContext ctx, final ByteBuf byteBuf, final List<Object> out)
        throws Exception {
        //byteBuf内容的基本校验,长度校验,magic校验
        if (byteBuf.readableBytes() > BASE_LEN) {
            if (byteBuf.readShort() != ImConstants.DEFAULT_MAGIC) {
                ctx.close();
                return;
            }
            int code = byteBuf.readInt();
            int len = byteBuf.readInt();
            if (byteBuf.readableBytes() < len) {
                ctx.close();
                return;
            }
            byte[] body = new byte[len];
            // 确保剩余byteBuf剩余消息长度足够
            byteBuf.readBytes(body);
            ImMsg imMsg = new ImMsg();
            imMsg.setCode(code);
            imMsg.setLen(len);
            imMsg.setBody(body);
            out.add(imMsg);
        }
    }

}
